package com.bw.services.IM

import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.View
import android.widget.ImageView
import android.app.AlertDialog
import android.widget.EditText
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bw.services.R
import com.hyphenate.EMContactListener
import com.hyphenate.chat.EMClient
import com.hyphenate.exceptions.HyphenateException
import com.therouter.router.Route
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
@Route(path = "app/IMmessageActivity")
class IMmessageActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_immessage)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
        // 新增：好友列表和添加好友按钮逻辑
        val rvFriendList = findViewById<RecyclerView>(R.id.rv_friend_list)
        val ivAddFriend = findViewById<ImageView>(R.id.iv_add_friend)
        val friendList = mutableListOf<Friend>()
        val adapter = FriendListAdapter(friendList) { friend ->
            val intent = Intent(this, IMChatActivity::class.java)
            intent.putExtra("username", friend.username)
            intent.putExtra("nickname", friend.nickname)
            startActivity(intent)
        }
        rvFriendList.layoutManager = LinearLayoutManager(this)
        rvFriendList.adapter = adapter
        // 加载好友列表
        Thread {
            try {
                val usernames = EMClient.getInstance().contactManager().allContactsFromServer
                // 可根据实际情况获取昵称、头像
                val list = usernames.map { Friend(it, it, null) }
                Handler(Looper.getMainLooper()).post {
                    friendList.clear()
                    friendList.addAll(list)
                    adapter.notifyDataSetChanged()
                }
            } catch (e: HyphenateException) {
                e.printStackTrace()
            }
        }.start()
        // 添加好友按钮点击
        ivAddFriend.setOnClickListener {
            // 新增：弹出输入框对话框，输入用户名后添加好友
            val editText = EditText(this)
            AlertDialog.Builder(this)
                .setTitle("添加好友")
                .setMessage("请输入对方用户名：")
                .setView(editText)
                .setPositiveButton("添加") { dialog, _ ->
                    val username = editText.text.toString().trim()
                    if (username.isNotEmpty()) {
                        Thread {
                            try {
                                EMClient.getInstance().contactManager().addContact(username, "请求添加好友")
                                runOnUiThread {
                                    Toast.makeText(this, "好友请求已发送", Toast.LENGTH_SHORT).show()
                                }
                            } catch (e: Exception) {
                                e.printStackTrace()
                                runOnUiThread {
                                    Toast.makeText(this, "添加失败：" + e.message, Toast.LENGTH_SHORT).show()
                                }
                            }
                        }.start()
                    } else {
                        Toast.makeText(this, "用户名不能为空", Toast.LENGTH_SHORT).show()
                    }
                    dialog.dismiss()
                }
                .setNegativeButton("取消") { dialog, _ -> dialog.dismiss() }
                .show()
        }
        // 监听好友变动，刷新列表
        EMClient.getInstance().contactManager().setContactListener(object : EMContactListener {
            override fun onContactAdded(username: String?) {
                // 刷新好友列表
            }
            override fun onContactDeleted(username: String?) {
                // 刷新好友列表
            }
            override fun onContactInvited(username: String?, reason: String?) {}
            override fun onFriendRequestAccepted(username: String?) {}
            override fun onFriendRequestDeclined(username: String?) {}
        })
        val ivBack = findViewById<ImageView>(R.id.iv_back)
        ivBack.setOnClickListener {
            finish()
        }
    }
}